<?php
namespace App\Services\Admin;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Log;

use App\Models\Menu AS MenuModel;

/**
 * 后台菜单处理
 * Class MenuService
 * @package App\Services\Admin
 */
class MenuService extends \App\Services\ComService
{
    /**
     * 获取前两级父的ID
     * @return array
     */
    public function getFatherMenuData(){
        $menuData = [];

        $menuObject = MenuModel::whereIn('level',[1,2])->orderBy('row_num', 'asc')->get();
        if(empty($menuObject)){
            return $menuData;
        }

        foreach ($menuObject as $key=>$val){
            if(empty($val)){
                continue;
            }
            $val = $val->toArray();
            $val['children'] = [];

            if(2 == $val['level'] && $val['father_id']){
                $menuData[$val['father_id']]['children'][$val['id']] = $val;
            } else if(1 == $val['level']){
                if(!empty($menuData[$val['id']]['children'])){
                    $val['children'] = $menuData[$val['id']]['children'];
                }
                $menuData[$val['id']] = $val;
            }

        }

        return $menuData;
    }

    /**
     * 获取所有菜单的树型数组
     * @return array
     */
    public function getAllMenuTreeArr(){
        $menuArr = [];
        $menuObject = MenuModel::orderBy('row_num', 'asc')->get();
        if(empty($menuObject)){
            return $menuArr;
        }

        foreach ($menuObject as $key=>$val){
            if(empty($val)){
                continue;
            }
            $val = $val->toArray();
            $val['children'] = [];

            if(3 == $val['level'] && !empty($val['path']) && !empty($val['father_id'])){
                $pathArr = explode(',', $val['path']);
                $val['children'] = [];
                $menuArr[$pathArr[0]]['children'][$val['father_id']]['children'][$val['id']] = $val;

            } else if(2 == $val['level'] && !empty($val['father_id'])){
                if(!empty($menuArr[$val['father_id']]['children'][$val['id']]['children'])){
                    $val['children'] = $menuArr[$val['father_id']]['children'][$val['id']]['children'];
                }
                $menuArr[$val['father_id']]['children'][$val['id']] = $val;
            } else {
                if(!empty($menuArr[$val['id']]['children'])){
                    $val['children'] = $menuArr[$val['id']]['children'];
                }
                $menuArr[$val['id']] = $val;
            }
        }

        return $menuArr;
    }

    /**
     * 获取显示于菜单的树型数据
     * @return array
     */
    public function getAdministratorMenu(){
        $menuArr = [];
        $menuObject = MenuModel::where('is_show', '=', 1)->orderBy('row_num', 'asc')->get();
        if(empty($menuObject)){
            return $menuArr;
        }

        foreach ($menuObject as $key=>$val){
            if(empty($val)){
                continue;
            }
            $val = $val->toArray();
            $val['children'] = [];
            unset($val['updated_at']);
            unset($val['created_at']);

            if(3 == $val['level'] && !empty($val['path']) && !empty($val['father_id'])){
                $pathArr = explode(',', $val['path']);
                $val['children'] = [];
                $menuArr[$pathArr[0]]['children'][$val['father_id']]['children'][$val['id']] = $val;

            } else if(2 == $val['level'] && !empty($val['father_id'])){
                if(!empty($menuArr[$val['father_id']]['children'][$val['id']]['children'])){
                    $val['children'] = $menuArr[$val['father_id']]['children'][$val['id']]['children'];
                }
                $menuArr[$val['father_id']]['children'][$val['id']] = $val;
            } else {
                if(!empty($menuArr[$val['id']]['children'])){
                    $val['children'] = $menuArr[$val['id']]['children'];
                }
                $menuArr[$val['id']] = $val;
            }
        }

        return $menuArr;
    }

    /**
     * 编辑或是更新菜单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveMenu(Request $request){
        $postData = $request->post();
        $postData['name'] = trim($postData['name']);
        $postData['url'] = !empty($postData['url']) ? trim($postData['url']) : null;
        $postData['row_num'] = intval($postData['row_num']);

        //编辑
        $menuObject = new MenuModel();
        if(!empty($postData['id'])){
            $menuObject = MenuModel::find($postData['id']);
            if(empty($menuObject)){
                return $this->responseError('编辑菜单不存在');
            }
        }

        //菜单名称的唯一性
//        if($menuObject->name != $postData['name']){
//            $menuValidateObject = MenuModel::where('name', '=', $postData['name'])->first();
//            if(!empty($menuValidateObject)){
//                return $this->responseError('菜单 【' . $postData['name'] . '】已经存在');
//            }
//        }

        //父ID处理
        $fatherId = $postData['father_id'];
        if($fatherId > 0){
            $fatherObject = MenuModel::find($fatherId);
            if(empty($fatherObject)){
                return $this->responseError('上级目录不存在');
            }
            if($fatherObject->level > 2){
                return $this->responseError('不能添加3级菜单');
            }

            $postData['father_id'] = $fatherObject->id;
            $postData['level'] = (int)$fatherObject->level + 1;
            if(!empty($fatherObject->father_id) && $fatherObject->father_id > 0){
                $postData['path'] = $fatherObject->father_id . ',' . $fatherObject->id;
            } else {
                $postData['path'] = $fatherObject->id;
            }
        } else {
            $postData['father_id'] = null;
            $postData['path'] = null;
            $postData['level'] = 1;
        }

        $menuObject->name = $postData['name'];
        $menuObject->url = $postData['url'];
        $menuObject->row_num = $postData['row_num'];
        $menuObject->icon = !empty(trim($postData['icon'])) ? trim($postData['icon']) : null;
        $menuObject->father_id = $postData['father_id'];
        $menuObject->path = $postData['path'];
        $menuObject->level = $postData['level'];
        $menuObject->is_show = $postData['is_show'];

        try{
            $menuObject->save();

            return $this->responseSuccess('操作成功');
        } catch (\Exception $e){
            return $this->responseError($e->getMessage());
        }


    }

    /**
     * 删除菜单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteMenu(Request $request){
        $id = $request->post('id');

        $childrenObject = MenuModel::where('father_id', '=', $id)->first();
        if(!empty($childrenObject)){
            return $this->responseError('删除菜单还有子菜单');
        }

        $menuObject = MenuModel::find($id);
        if(empty($menuObject)){
            return $this->responseError('删除的菜单信息不存在');
        }

        try{
            $menuObject->delete();
            return $this->responseSuccess([], '操作成功');
        }catch (\Exception $e){
            return $this->responseError($e->getMessage());
        }
    }

    /**
     * 根据ID获取菜单对应的数据
     * @param $id
     * @return mixed
     */
    public function getMenuObject($id){
        return MenuModel::find($id);
    }

    /**
     * 根据ID集，获取对应的数据
     * @param array $ids
     * @return array
     */
    public function getMenuArrWhereIn($ids=[]){
        if(empty($ids)){
            $returnArr = MenuModel::get();
        } else {
            $returnArr = MenuModel::whereIn('id', $ids)->get();
        }
        return !empty($returnArr) ? $returnArr->toArray() : [];
    }
}
